<template>
  <div>
    <el-button type="primary" @click="handleAddDoctor">添加医生</el-button><el-input
      v-model="input"
      style="width: 240px; margin-left: 20px;"
      :prefix-icon="Search"
      placeholder="请输入姓名"
      @keyup.enter="search"
    />
    <el-button type="info" plain @click="reset">重置</el-button>
    <el-table v-if="active" :data="filteredItems" style="width: 100%; margin-top: 20px" border :table-layout="'fixed'">
      <el-table-column prop="id" label="医生ID" width="100" />
      <el-table-column prop="name" label="姓名" width="120" />
      <el-table-column prop="gender" label="性别" width="80">
        <template #default="scope">
          {{ scope.row.gender === 'M' ? '男' : '女' }}
        </template>
      </el-table-column>
      <el-table-column prop="specialty" label="科室" width="120" />
      <el-table-column prop="hospital_id" label="所在医院" width="180">
        <template #default="scope">
          {{ hospitalMap[scope.row.hospital_id] }}
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="电话号码" width="120" />
      <el-table-column prop="email" label="电子邮箱" width="180" />
      <el-table-column prop="position" label="职位" width="120" />
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      style="margin-top: 20px"
      background
      layout="prev, pager, next"
      :total="total"
      :page-size="pageSize"
      v-model:current-page="currentPage"
      @current-change="handlePageChange"
    />
    <el-dialog v-model="dialogVisible" title="添加医生" width="50%">
      <el-form :model="formModel" :rules="formRules" ref="form" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="formModel.name" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="formModel.gender">
                <el-radio value="M">男</el-radio>
                <el-radio value="F">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="科室" prop="specialty">
              <el-select v-model="formModel.specialty" style="width: 100%">
                <el-option
                  v-for="department in departments"
                  :key="department.id"
                  :label="department.name"
                  :value="department.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="医院" prop="hospital_id">
              <el-select v-model="formModel.hospital_id" style="width: 100%">
                <el-option
                  v-for="hospital in hospitals"
                  :key="hospital.id"
                  :label="hospital.name"
                  :value="hospital.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="电话号码" prop="phone">
              <el-input v-model="formModel.phone" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电子邮箱" prop="email">
              <el-input v-model="formModel.email" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="职位" prop="position">
              <el-input v-model="formModel.position" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="editDialogVisible" title="编辑医生" width="50%">
      <el-form :model="editFormModel" :rules="formRules" ref="editForm" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="editFormModel.name" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="editFormModel.gender">
                <el-radio value="M">男</el-radio>
                <el-radio value="F">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="科室" prop="specialty">
              <el-select v-model="editFormModel.specialty" style="width: 100%">
                <el-option
                  v-for="department in departments"
                  :key="department.id"
                  :label="department.name"
                  :value="department.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="医院" prop="hospital_id">
              <el-select v-model="editFormModel.hospital_id" style="width: 100%">
                <el-option
                  v-for="hospital in hospitals"
                  :key="hospital.id"
                  :label="hospital.name"
                  :value="hospital.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="电话号码" prop="phone">
              <el-input v-model="editFormModel.phone" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电子邮箱" prop="email">
              <el-input v-model="editFormModel.email" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="职位" prop="position">
              <el-input v-model="editFormModel.position" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEditForm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getDoctor, getHospital, getDepartment } from '@/api/getInfo'
import { addDoctor, updateDoctor, deleteDoctor } from '@/api/doctorManage'
import { Search } from '@element-plus/icons-vue'

const doctorList = ref([])
const total = ref(0)
const pageSize = ref(10)
const active = ref(true)
const hospitalMap = ref({})
const input = ref('')
const dialogVisible = ref(false)
const editDialogVisible = ref(false)
const hospitals = ref([])
const departments = ref([])
const specialtyMap = ref({})

// 添加表单数据
const formModel = ref({
  name: '',
  gender: 'M',
  specialty: '',
  hospital_id: '',
  phone: '',
  email: '',
  position: ''
})

function resetForm() {
  formModel.value = {
    name: '',
    gender: 'M',
    specialty: '',
    hospital_id: '',
    phone: '',
    email: '',
    position: ''
  }
}

// 编辑表单数据
const editFormModel = ref({
  id: '',
  name: '',
  gender: 'M',
  specialty: '',
  hospital_id: '',
  phone: '',
  email: '',
  position: ''
})

// 表单验证规则
const formRules = ref({
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  specialty: [
    { required: true, message: '请输入科室', trigger: 'blur' }
  ],
  hospital_id: [
    { required: true, message: '请选择医院', trigger: 'change' }
  ]
})

// 搜索医生
async function search() {
  currentPage.value = 1
  const res = await getDoctor({ name: input.value.trim() })
  doctorList.value = res.data
  total.value = res.data?.length
}

// 重置搜索
function reset() {
  input.value = ''
  fetchDoctors()
}

// 获取医生列表
const fetchDoctors = async () => {
  // TODO: 调用API获取医生数据
  const res = await getDoctor()
  doctorList.value = res.data
  total.value = res.data?.length
}

// 获取医院列表
const fetchHospitals = async () => {
  const res = await getHospital()
  hospitals.value = res.data
  hospitalMap.value = res.data.reduce((map, hospital) => {
    map[hospital.id] = hospital.name
    return map
  }, {})
}

// 获取部门列表
const fetchDepartments = async () => {
  const res = await getDepartment();
  console.log(res.data);

  // 使用 Map 去重，基于部门的 name
  const uniqueDepartments = new Map();
  res.data.forEach(department => {
    if (!uniqueDepartments.has(department.name)) {
      uniqueDepartments.set(department.name, department);
    }
  });

  // 将去重后的部门列表赋值给 departments
  departments.value = Array.from(uniqueDepartments.values());

  // 构建 specialtyMap
  specialtyMap.value = departments.value.reduce((map, department) => {
    map[department.id] = department.name;
    return map;
  }, {});
}


// 添加医生
const handleAddDoctor = () => {
  dialogVisible.value = true
}

// 编辑医生
const handleEdit = (row) => {
  handleEditDoctor(row)
}

const handleEditDoctor = (doctor) => {
  editFormModel.value = {
    id: doctor.id,
    name: doctor.name,
    gender: doctor.gender,
    specialty: doctor.specialty,
    hospital_id: doctor.hospital_id,
    phone: doctor.phone,
    email: doctor.email,
    position: doctor.position
  }
  editDialogVisible.value = true
}

// 删除医生
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该医生吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
  }).then(async () => {
    // TODO: 调用API删除医生
    const res = await deleteDoctor({ 
      id: row.id ,
      hospital_id: row.hospital_id,
      specialty: row.specialty
    })
    if (res.status) {
      ElMessage.error(res.msg)
      return
    }
    ElMessage.success('删除成功')
    fetchDoctors()
  })
}

// 分页
const handlePageChange = () => {
  fetchDoctors()
}
// 当前页默认为1
const currentPage = ref(1)
// 过滤后的数据
const filteredItems = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value;
    return doctorList.value.slice(start, start + pageSize.value); // 根据当前页和每页条数获取数据
})

// 添加医生
const submitForm = async () => {
  try {
    const formData = {
      ...formModel.value,
      specialty: departments.value.find(d => d.id === formModel.value.specialty)?.name || ''
    }
    const res = await addDoctor(formData)
    if (res.status) {
      ElMessage.error(res.msg)
      return
    }
    ElMessage.success('添加医生成功')
    dialogVisible.value = false
    fetchDoctors()
    resetForm()
  } catch (error) {
    console.log(error)
    ElMessage.error('添加医生失败')
  }
}

// 更新医生
const submitEditForm = async () => {
  try {
    const formData = {
      ...editFormModel.value,
      specialty: departments.value.find(d => d.id === editFormModel.value.specialty)?.name || editFormModel.value.specialty
    }
    console.log(formData,'edit')
    const res = await updateDoctor(formData)
    if (res.status) {
      ElMessage.error(res.msg)
      return
    }
    ElMessage.success('更新医生成功')
    editDialogVisible.value = false
    fetchDoctors()
  } catch (error) {
    ElMessage.error('更新医生失败')
  }
}

onMounted(async () => {
  active.value = true
  await fetchHospitals()
  await fetchDoctors()
  await fetchDepartments()
})

onBeforeUnmount(() => {
  active.value = false
})
</script>
